package top.hzy520.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import top.hzy520.common.constants.Parameters;

/**
 * @Author: HouZeYu
 * @Description:  SpringSecurity配置
 * @Date: Created in 15:47 2018/7/8
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
        @Autowired
        private Parameters parameters;
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return new TokenAuthenticationManager();
    }
    private TokenAuthenticationFilter getTokenAuthenticationFilter() throws Exception {
        TokenAuthenticationFilter filter=new TokenAuthenticationFilter(parameters.getNoneSecurityPath());
        filter.setAuthenticationManager(this.authenticationManagerBean());
        return filter;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
     http.csrf().disable()
             .authorizeRequests()
             .antMatchers(parameters.getNoneSecurityPath().toArray(new String[parameters.getNoneSecurityPath().size()])).permitAll()
             .anyRequest().authenticated()
             .and()
             .httpBasic().authenticationEntryPoint(new UnauthorizedEntryPoint())
             .and()
             .sessionManagement().sessionFixation().none().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //无状态请求不需要session
             .and()
             .addFilter(getTokenAuthenticationFilter());
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**")//忽略 OPTIONS 方法的请求
      .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");
        //放过swagger
    }
}
